package com.jushu.storbox.actions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.jushu.storbox.FileDownloadActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.ViewActivity;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.database.IShareINodeDao;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.entities.FolderInfo;
import com.jushu.storbox.entities.ShareINode;
import com.jushu.storbox.entities.SharedUser;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.manager.CatchManager;
import com.jushu.storbox.newservice.IShareService;
import com.jushu.storbox.newservice.RemoteShareService;
import com.jushu.storbox.service.ServiceFactory;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.jushu.storbox.vo.PagedList;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.request.CopyFileRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderCopyRequstV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.MyShareListRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.Order;
import com.huawei.sharedrive.sdk.android.modelV2.request.ShareInfo;
import com.huawei.sharedrive.sdk.android.modelV2.request.ShareToMeRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.SharedUserV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.ThumbnailRequest;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderResponse;
import com.huawei.sharedrive.sdk.android.modelV2.response.INodeShareV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.ShareResourceV2;
import com.huawei.sharedrive.sdk.android.serviceV2.ShareClientV2;

public class ActionShare extends BaseAction {
	
	private static final String TAG = ActionShare.class.getSimpleName();

	public void batchShare(Context context, Handler msgHandler,
			final List<SharedUserV2> putShareRequest, final ShareInfo shareInfo) {
		LogUtil.i(TAG, "batchShare[Actions]");
		executeRunTask(new RealTaskRunnable(context, msgHandler){
			@Override
			protected void doTask(Context context, Handler msgHandler)
					throws ClientException {
				ShareClientV2.getInstance().batchAddShareResource(
						ShareDriveApplication.getInstance().getAuthorization(),
						putShareRequest,  shareInfo);
				Message msg = msgHandler.obtainMessage();
				msg.what = UiConstant.SHARE_ACTION_EXECUTE_SHARE_SHIPS_SUCCESS;
				msg.obj = shareInfo;
				msg.sendToTarget();
			}
		});
	}
	
	public void deleteShareShips(final Context context, final SharedUser sharedUser, 
			final String ownerId, final Handler msgHandler) {

		executeRunTask(new RealTaskRunnable(context, msgHandler) {
			@Override
			protected void doTask(Context context, Handler msgHandler) throws ClientException {

			}
		});


		executeRunTask(new RealTaskRunnable(context, msgHandler) {
			protected void doTask(Context context, Handler msgHandler) throws ClientException {
				ShareClientV2.getInstance().deleteShareShips(
					ShareDriveApplication.getInstance().getAuthorization(), 
					String.valueOf(sharedUser.getSharedUserId()),
					sharedUser.getSharedUserType(), ownerId, 
					String.valueOf(sharedUser.getiNodeId()));
				Message msg = msgHandler.obtainMessage();
				msg.what = UiConstant.SHARE_ACTION_DELETE_SHARE_SHIPS_SUCCESS;
				msg.obj = sharedUser;
				msg.sendToTarget();
			}
		});
	}
	
	public void deleteShareShips(final Context context, final SharedUserV2 sharedUser, 
			final String ownerId, final String iNodeId, final Handler msgHandler) {
		executeRunTask(new RealTaskRunnable(context, msgHandler) {
			protected void doTask(Context context, Handler msgHandler) throws ClientException {
				ShareClientV2.getInstance().deleteShareShips(
					ShareDriveApplication.getInstance().getAuthorization(), 
					sharedUser, ownerId, iNodeId);
				Message msg = msgHandler.obtainMessage();
				msg.what = UiConstant.SHARE_ACTION_DELETE_SHARE_SHIPS_SUCCESS;
				msg.obj = sharedUser;
				msg.sendToTarget();
			}
		});
	}
	
	public void deleteShareShips(final Context context, final SharedUserV2 sharedUser, 
			final INodeShareV2 node, final Handler msgHandler) {
		executeRunTask(new RealTaskRunnable(context, msgHandler) {
			protected void doTask(Context context, Handler msgHandler) throws ClientException {
				ShareClientV2.getInstance().deleteShareShips(
					ShareDriveApplication.getInstance().getAuthorization(), 
					sharedUser, String.valueOf(node.getOwnerId()), String.valueOf(node.getNodeId()));
				Message msg = msgHandler.obtainMessage();
				msg.what = UiConstant.SHARE_ACTION_DELETE_SHARE_SHIPS_SUCCESS;
				msg.obj = node;
				msg.sendToTarget();
			}
		});
	}
	
	public void deleteAllShareShips(Context context, Handler msgHandler,
			final String ownerId, final String iNodeId ) {
		executeRunTask(new RealTaskRunnable(context, msgHandler) {
			protected void doTask(Context context, Handler msgHandler) throws ClientException {
				ShareClientV2.getInstance().deleteShareShips(
					ShareDriveApplication.getInstance().getAuthorization(), 
					null, ownerId, iNodeId);
				Message msg = msgHandler.obtainMessage();
				msg.what = UiConstant.SHARE_ACTION_DELETE_ALL_SHARE_SHIPS_SUCCESS;
				msg.sendToTarget();
			}
		});
	}
	
	public void getSharedResourceByMe(final Context context,final int offset, 
			final int limit, final Handler msgHandler) {
		executeRunTask(new RealTaskRunnable(context, msgHandler){
			protected void doTask(Context context, Handler msgHandler)  throws ClientException {
				MyShareListRequestV2 request = new MyShareListRequestV2();
				request.setOffset(offset);
				request.setLimit(limit);
				
				List<Order> orderList = new ArrayList<Order>();
				orderList.add(new Order("name", "ASC"));
				request.setOrder(orderList);
				
				List<ThumbnailRequest> thumbnailList = new ArrayList<ThumbnailRequest>();
				thumbnailList.add(new ThumbnailRequest(
						ClientConfig.THUMBNAIL_WIDTH, ClientConfig.THUMBNAIL_HEIGHT));
				request.setThumbnail(thumbnailList);
				
				ShareResourceV2 response = ShareClientV2.getInstance().listShareResourceByMe(
						ShareDriveApplication.getInstance().getAuthorization(),
						request);
				//response
				Message msg = msgHandler.obtainMessage();
				msg.what = UiConstant.SHARE_ACTION_GET_SHARE_RESOURCE_BYME;
				msg.obj = response.getContents();
				msg.sendToTarget();
				
				//do update to local database
			}
		});
	}
	
	public void getSharedResourceToMe(final Context context,final int pageIndex, 
			final int limit,final String keyWord, final Handler msgHandler) {
		executeRunTask(new RealTaskRunnable(context, msgHandler){
			protected void doTask(Context context, Handler msgHandler)  throws ClientException {
				
				IShareService shareService = new RemoteShareService();
				ShareResourceV2 response = shareService.getSharedResourceToMe(pageIndex, limit, keyWord);
				
				//process response
				Message msg = msgHandler.obtainMessage();
				msg.what = UiConstant.SHARE_ACTION_GET_SHARE_RESOURCE_TOME;
				msg.obj = response.getContents();
				msg.sendToTarget();
				
				//do update to local database
				List<INodeShareV2> list = response.getContents();
				if(list != null) {
					IShareINodeDao shareNodeDao = DAOFactory.instance(context).getShareINodeDao();
					for(INodeShareV2 node : list) {
						ShareINode localNode = CatchManager.getInstance().getShareINode(node);
						if(localNode == null) {
							localNode = new ShareINode();
							localNode.valueOf(node);
							//add to catch
							CatchManager.getInstance().putShareINode(node, localNode);
							
							//add to database
							ShareINode inode = shareNodeDao.getShareINode(node);
							if(inode == null) {
								shareNodeDao.insertFolderOrFile(node);
							}
						}
					}
				}
			}
		});
	}
	
	public void getSharedResourceByMeV2(final Context context,final int offset, 
			final int limit, final Handler msgHandler) {
		executeRunTask(new RealTaskRunnable(context, msgHandler){
			protected void doTask(Context context, Handler msgHandler)  throws ClientException {
				MyShareListRequestV2 request = new MyShareListRequestV2();
				request.setOffset(offset);
				request.setLimit(limit);
				
				List<Order> orderList = new ArrayList<Order>();
				orderList.add(new Order("name", "AES"));
				request.setOrder(orderList);
				
				List<ThumbnailRequest> thumbnailList = new ArrayList<ThumbnailRequest>();
				thumbnailList.add(new ThumbnailRequest(
						ClientConfig.THUMBNAIL_WIDTH, ClientConfig.THUMBNAIL_HEIGHT));
				request.setThumbnail(thumbnailList);
				
				ShareResourceV2 response = ShareClientV2.getInstance().listShareResourceByMe(
						ShareDriveApplication.getInstance().getAuthorization(),
						request);
				//response
				PagedList<FileFolderInfo> pagedList = new PagedList<FileFolderInfo>();
				List<INodeShareV2> remoteDatas = response.getContents();
				List<FileFolderInfo> dataList = new ArrayList<FileFolderInfo>();
				for(int i=0; i<remoteDatas.size(); i++) {
					ShareINode node = new ShareINode();
					node.valueOf(remoteDatas.get(i));
					dataList.add(node);
				}
				
				pagedList.setPagedList(dataList);
				pagedList.setTotal(remoteDatas.size());
				pagedList.setPageNumber(0);
				pagedList.setPagedFolderId("0");
				pagedList.setPagedFolderName("My Share");
				
				Message msg = msgHandler.obtainMessage();
				msg.what = UiConstant.SHARE_ACTION_GET_SHARE_RESOURCE_BYME;
				msg.obj = pagedList;
				msg.sendToTarget();
				
				//do update to local database
			}
		});
	}
	
	public void getSharedResourceToMeV2(final Context context,final int offset, 
			final int limit,final String keyWord, final Handler msgHandler) {
		executeRunTask(new RealTaskRunnable(context, msgHandler){
			protected void doTask(Context context, Handler msgHandler)  throws ClientException {
				List<Order> orderList = new ArrayList<Order>();
				orderList.add(new Order("name", "AES"));
				List<ThumbnailRequest> thumbnailList = new ArrayList<ThumbnailRequest>();
				thumbnailList.add(new ThumbnailRequest(
						ClientConfig.THUMBNAIL_WIDTH, ClientConfig.THUMBNAIL_HEIGHT));
				
				ShareToMeRequestV2 request = new ShareToMeRequestV2();
				request.setOffset(offset);
				request.setLimit(limit);
				request.setOrder(orderList);
				request.setThumbnail(thumbnailList);
				request.setKeyword(keyWord);
				
				ShareResourceV2 response = ShareClientV2.getInstance().listShareResourceToMe(
						ShareDriveApplication.getInstance().getAuthorization(),
						request);
				//process response
				PagedList<FileFolderInfo> pagedList = new PagedList<FileFolderInfo>();
				List<INodeShareV2> remoteDatas = response.getContents();
				List<FileFolderInfo> dataList = new ArrayList<FileFolderInfo>();
				for(int i=0; i<remoteDatas.size(); i++) {
					ShareINode node = new ShareINode();
					node.valueOf(remoteDatas.get(i));
					dataList.add(node);
				}
				
				pagedList.setPagedList(dataList);
				pagedList.setTotal(remoteDatas.size());
				pagedList.setPageNumber(0);
				pagedList.setPagedFolderId("0");
				pagedList.setPagedFolderName(context.getResources().getString(R.string.share_fragment_my_share));
				
				Message msg = msgHandler.obtainMessage();
				msg.what = UiConstant.SHARE_ACTION_GET_SHARE_RESOURCE_TOME;
				msg.obj = pagedList;
				msg.sendToTarget();
				
				//do update to local database
				
			}
		});
	}

	public void copyShareFile(final Context context, final int messageCode,
			final String resourceOwnerId, final String resourceId, 
			final String targetOwnerId, final String targetFolderId, 
			final Handler msgHandler) {
		executeRunTask(new RealTaskRunnable(context, msgHandler) {
			protected void doTask(Context context, Handler msgHandler) throws ClientException {
				//init request data
				CopyFileRequestV2 request = new CopyFileRequestV2();
				request.setAutoRename(false);
				request.setDestOwnerId(Long.valueOf(targetOwnerId));
				request.setDestParent(Long.valueOf(targetFolderId));
				request.setLink(null);
				//request server do task
				FileInfoResponseV2 response = ServiceFactory.getRemoteFileService().copyFile(resourceOwnerId, resourceId, request);
				//fill response
				FileInfo info = new FileInfo();
				info.valueOf(response);
				//send message to caller
				Message msg = msgHandler.obtainMessage();
				msg.what = messageCode;
				msg.obj = info;
				msg.sendToTarget();
				//after finished copy
				DAOFactory.instance(context).getFileDao().insertFile(response);
			    DAOFactory.instance(context).getFolderDao().setChangedFolderId(targetOwnerId, targetFolderId, "1");
			}

			@Override
			protected boolean filterException(ClientException e, final Handler handler) {
				if(e.getStatusCode() == ClientExceptionRelateHandler.ERROR_CODE_409_SOURCE_CONFLICT
						&& ClientExceptionRelateHandler.RepeatNameConflict.equals(e.getCode())) {
		            handler.post(new Runnable(){
						@Override
						public void run() {
							final ClouddriveDialog move = new ClouddriveDialog(context, R.style.dialog_upload,
					                R.layout.dialog_filedelete);
				            View conventView = move.getConventView();
				            Button dialog_cancal = (Button) conventView.findViewById(R.id.dialog_add_file_cancal_bt);
				            Button dialog_OK = (Button) conventView.findViewById(R.id.dialog_add_file_ok_bt);
				            TextView dialog_prompt_tv = (TextView) conventView.findViewById(R.id.dialog_prompt_tv);
				            dialog_prompt_tv.setText(context.getString(R.string.allfile_confirm_reanme_filefolder));
				            dialog_cancal.setOnClickListener(new View.OnClickListener() {
				                @Override
				                public void onClick(View v) {
				                	move.dismiss();//共享文件取消自动重命名|团队空间转存到我的云盘取消自动重命名|文件转存到团队空间
				                	handler.sendEmptyMessage(UiConstant.SHARE_ACTION_SAVE_CANCEL);
				                }
				            });
				            dialog_OK.setOnClickListener(new View.OnClickListener() {
				                @Override
				                public void onClick(View v) {
				                	move.dismiss();
				                	saveFileWithAutoRename(context, messageCode, resourceOwnerId, resourceId, targetOwnerId, targetFolderId, handler);
				                }
				            });
				            move.show();
						}
		            });
					return true;
				} else {
					return false;
				}
			}

		});
	}
	
	void saveFileWithAutoRename(final Context context, final int messageCode,
			final String resourceOwnerId, final String resourceId, 
			final String targetOwnerId, final String targetFolderId, 
			final Handler msgHandler){
		executeRunTask(new RealTaskRunnable(context, msgHandler) {
			protected void doTask(Context context, Handler msgHandler) throws ClientException {
				//init request data
				CopyFileRequestV2 request = new CopyFileRequestV2();
				request.setAutoRename(true);
				request.setDestOwnerId(Long.valueOf(targetOwnerId));
				request.setDestParent(Long.valueOf(targetFolderId));
				request.setLink(null);
				//request server do task
				FileInfoResponseV2 response = ServiceFactory.getRemoteFileService().copyFile(resourceOwnerId, resourceId, request);
				//fill response
				FileInfo info = new FileInfo();
				info.valueOf(response);
				//send message to caller
				Message msg = msgHandler.obtainMessage();
				msg.what = messageCode;
				msg.obj = info;
				msg.sendToTarget();
				//after finished copy
				DAOFactory.instance(context).getFileDao().insertFile(response);
			    DAOFactory.instance(context).getFolderDao().setChangedFolderId(targetOwnerId, targetFolderId, "1");
			}
		});
	}
	
	public void copyShareFolder(final Context context, final int messageCode,
			final String resourceOwnerId, final String resourceId, 
			final String targetOwnerId, final String targetFolderId, 
			final Handler msgHandler) {
		executeRunTask(new RealTaskRunnable(context, msgHandler) {
			protected void doTask(Context context, Handler msgHandler) throws ClientException {
				//init request data
				FolderCopyRequstV2 request = new FolderCopyRequstV2();
				request.setDestParent(targetFolderId);
				request.setDestOwnerId(targetOwnerId);
				request.setAutoRename(false);
				//request server do task
				FolderResponse response = ServiceFactory.getRemoteFolderService().copyFolder(resourceOwnerId, resourceId, request);
				//fill response
				FolderInfo info = new FolderInfo();
				info.valueOf(response);
				//send message to caller
				Message msg = msgHandler.obtainMessage();
				msg.what = messageCode;
				msg.obj = info;
				msg.sendToTarget();
				//after finished copy
				DAOFactory.instance(context).getFolderDao().insertFolder(response, Constant.DOWNLOAD_STATUS_NOCACHE_DB);
				DAOFactory.instance(context).getFolderDao().setChangedFolderId(targetOwnerId, targetFolderId, "1");
			}

			@Override
			protected boolean filterException(ClientException e, final Handler handler) {
				if(e.getStatusCode() == ClientExceptionRelateHandler.ERROR_CODE_409_SOURCE_CONFLICT
						&& ClientExceptionRelateHandler.RepeatNameConflict.equals(e.getCode())) {
		            handler.post(new Runnable(){
						@Override
						public void run() {
							final ClouddriveDialog move = new ClouddriveDialog(context, R.style.dialog_upload,
					                R.layout.dialog_filedelete);
				            View conventView = move.getConventView();
				            Button dialog_cancal = (Button) conventView.findViewById(R.id.dialog_add_file_cancal_bt);
				            Button dialog_OK = (Button) conventView.findViewById(R.id.dialog_add_file_ok_bt);
				            TextView dialog_prompt_tv = (TextView) conventView.findViewById(R.id.dialog_prompt_tv);
				            dialog_prompt_tv.setText(context.getString(R.string.allfile_confirm_reanme_filefolder));
				            dialog_cancal.setOnClickListener(new View.OnClickListener() {
				                @Override
				                public void onClick(View v) {
				                	move.dismiss();//共享文件夹取消自动重命名 |团队空间转存到我的云盘取消自动重命名
				                	handler.sendEmptyMessage(UiConstant.SHARE_ACTION_SAVE_CANCEL);
				                }
				            });
				            dialog_OK.setOnClickListener(new View.OnClickListener() {
				                @Override
				                public void onClick(View v) {
				                	move.dismiss();
				                	saveFolderWithAutoRename(context, messageCode, resourceOwnerId, resourceId, targetOwnerId, targetFolderId, handler);
				                }
				            });
				            move.show();
						}
		            });
					return true;
				} else {
					return false;
				}
			}
			
		});
	}

	void saveFolderWithAutoRename(final Context context, final int messageCode,
			final String resourceOwnerId, final String resourceId, 
			final String targetOwnerId, final String targetFolderId, 
			final Handler msgHandler){
		executeRunTask(new RealTaskRunnable(context, msgHandler) {
			protected void doTask(Context context, Handler msgHandler) throws ClientException {
				//init request data
				FolderCopyRequstV2 request = new FolderCopyRequstV2();
				request.setDestParent(targetFolderId);
				request.setDestOwnerId(targetOwnerId);
				request.setAutoRename(true);
				//request server do task
				FolderResponse response = ServiceFactory.getRemoteFolderService().copyFolder(resourceOwnerId, resourceId, request);
				//fill response
				FolderInfo info = new FolderInfo();
				info.valueOf(response);
				//send message to caller
				Message msg = msgHandler.obtainMessage();
				msg.what = messageCode;
				msg.obj = info;
				msg.sendToTarget();
				//after finished copy
				DAOFactory.instance(context).getFolderDao().insertFolder(response, Constant.DOWNLOAD_STATUS_NOCACHE_DB);
				DAOFactory.instance(context).getFolderDao().setChangedFolderId(targetOwnerId, targetFolderId, "1");
			}
		});
	
	}
	
	public void openOtherShareINodeFile(final Context context,
			final INodeShareV2 sourceNode, 
			final Handler messageHandler) {
		String path = DirectoryUtil.generateShareDownloadPath(context, 
				sourceNode.getOwnerId(),
				sourceNode.getNodeId(), 
				sourceNode.getName());
		File file = new File(path);
		if(file.exists()) {
			Intent intent = new Intent(context, ViewActivity.class);
	        intent.putExtra("view_mdm_path", path);
	        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        context.startActivity(intent);
		} else {
			ShareINode shareNode = new ShareINode();
			shareNode.valueOf(sourceNode);
			Intent intent = new Intent(context, FileDownloadActivity.class);
			intent.putExtra(ClientConfig.FILE_FOLDER_INFO, shareNode);
	        context.startActivity(intent);
		}
	}
	
	public void openMyShareINodeFile(final Context context,
			final INodeShareV2 sourceNode, 
			final Handler messageHandler) {
		String path = DirectoryUtil.generateFileDownloadPath(context, 
				sourceNode.getOwnerId().toString(), sourceNode.getNodeId().toString(), sourceNode.getName());
		File file = new File(path);
		if(file.exists()) {
			Intent intent = new Intent(context, ViewActivity.class);
	        intent.putExtra("view_mdm_path", path);
	        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        context.startActivity(intent);
		} else {
			FileFolderInfo shareNode = new ShareINode();
			shareNode.setType(sourceNode.getType());
			shareNode.setOwnerBy(sourceNode.getOwnerId().toString());
			shareNode.setOwnerName(sourceNode.getOwnerName());
			shareNode.setSharedUserId(Long.valueOf(ShareDriveApplication.getInstance().getWnerID()));
			shareNode.setiNodeId(sourceNode.getNodeId().toString());
			shareNode.setId(sourceNode.getNodeId().toString());
			shareNode.setName(sourceNode.getName());
			shareNode.setSize(sourceNode.getSize());
			Intent intent = new Intent(context, FileDownloadActivity.class);
			intent.putExtra(ClientConfig.FILE_FOLDER_INFO, shareNode);
	        context.startActivity(intent);
		}
	}
	
	public void openOthersShare(final Context context,
			final FileFolderInfo sourceNode, 
			final Handler messageHandler) {
		String path = DirectoryUtil.generateShareDownloadPath(context, 
				sourceNode.getOwnerId(),
				sourceNode.getId(),
				sourceNode.getName());
		File file = new File(path);
		if(file.exists()) {
			Intent intent = new Intent(context, ViewActivity.class);
	        intent.putExtra("view_mdm_path", path);
	        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        context.startActivity(intent);
		} else {
			sourceNode.setIsInode(1);
			Intent intent = new Intent(context, FileDownloadActivity.class);
			intent.putExtra(ClientConfig.FILE_FOLDER_INFO, sourceNode);
	        context.startActivity(intent);
		}
	}
}
